/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.support.dev.order.notify;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yanlight.Constants;

/**
 * 
 * @author haolw
 * @time 2018/02/25
 */
class DevOrderTaskProcessor implements Runnable {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private DevOrderNotifyDispatcher notifyDispatcher;
	private DevOrderStorageDispatcher storageDispatcher;
	private final DevOrderNotifyTask notifyTask;

	public DevOrderTaskProcessor() {
		this(null);
	}

	public DevOrderTaskProcessor(DevOrderNotifyTask notifyTask) {
		this.notifyTask = notifyTask;
	}

	@Override
	public void run() {
		logger.info("*********dev.order.nofify*********");
		StringBuilder builder = new StringBuilder();
		builder.append("outTradeNo:" + notifyTask.getOutTradeNo() + "\n");
		builder.append("url:" + notifyTask.getNotifyUrl() + "\n");
		builder.append("payTime:" + notifyTask.getPayTime() + "\n");
		builder.append("payType:" + notifyTask.getPayType() + "\n");
		builder.append("loop:" + notifyTask.getLoopCount());
		String result = null;
		try {
			result = notifyTask.execute();
			builder.append("\n"+"result:" + result);
		} catch (Exception e) {
			logger.info(builder.toString());
			e.printStackTrace();
			notifyTask.loop();
			notifyDispatcher.addTask(notifyTask);
			return;
		}
		if (Constants.SUCCESS.equals(result)) {
			storageDispatcher.addTask(notifyTask.getOutTradeNo());
			logger.info(builder.toString());
			return;
		}
		notifyTask.loop();
		notifyDispatcher.addTask(notifyTask);
		logger.info(builder.toString());
	}

	public void setNotifyDispatcher(DevOrderNotifyDispatcher notifyDispatcher) {
		this.notifyDispatcher = notifyDispatcher;
	}

	public void setStorageDispatcher(DevOrderStorageDispatcher storageDispatcher) {
		this.storageDispatcher = storageDispatcher;
	}

}
